<template>
  <main-card title="数据管理" :loading="loading" :show-screen-space="false" :online-lab="true">
    <template #title>
      <div class="title-wrap">
        <div class="title">数据管理</div>

        <div class="display-btns">
          <div :class="['btn', !active && 'active']" style="padding-left: 8px" @click="activeSwitch">
            <img class="logo" :src="!active ? listCheckActive : listCheckDefult" />
          </div>
          <div :class="['btn', active && 'active']" @click="activeSwitch">
            <img class="logo" :src="active ? layoutActive : layoutDefault" />
          </div>
        </div>
      </div>
    </template>
    <template #tool-btn v-if="!active">
      <a-button
        type="text"
        class="icon-only-btn"
        style="width: 36px; height: 36px"
        @click="fileTaskStore.changeTaskListOptions({ open: true })"
      >
        <i class="iconfont icon-tasklist-line" style="font-size: 18px"></i>
      </a-button>
      <a-button class="ml-8" type="primary" @click="handleOpenDataSetForm('add')"> 创建数据集 </a-button>
    </template>
    <div v-if="!active" class="mb-48 fbc">
      <a-select v-model:value="pageForm.filter" class="w-140" :options="headerSearchSelectOptions" @change="onSelectChange" />
      <div class="flex-1"></div>
      <a-input
        v-model:value="pageForm.name"
        v-trim
        class="h-36"
        allow-clear
        placeholder="请输入名称"
        style="width: 328px"
        @keyup.enter="getDataList({ offset: 1 })"
      >
        <template #prefix> <i class="iconfont icon-search-line"></i> </template>
      </a-input>
    </div>

    <div v-if="!active" class="page-table">
      <a-table
        :columns="tableColumns"
        :data-source="dataList"
        :pagination="false"
        :style="{ width: '100%' }"
        :custom-row="r => ({ onClick: () => handleToDetail(r.id) })"
        @change="tableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'size'">
            {{ sizeFilter(record?.size || 0) }}
          </template>
          <template v-else-if="column.dataIndex === 'operate'">
            <a-dropdown placement="bottom" @click.stop>
              <a-button :data-share="record?.createType === 1" type="text" class="icon-only-btn" @click.stop>
                <i class="iconfont icon-more-line"></i>
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="handleOpenDataSetForm('edit', record)"
                  >
                    编辑
                  </a-menu-item>
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="handleDeleteDateSet(record)"
                  >
                    删除
                  </a-menu-item>
                  <a-menu-item class="menu-icon-item" @click="handleOverview(record)"> 概览 </a-menu-item>
                  <a-menu-item class="menu-icon-item" @click="handleDownLoad(record)"> 下载 </a-menu-item>
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="handleOpenShareModal(record)"
                  >
                    分享
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
          <template v-else>
            <span :title="replaceEmptyStr(record[column.dataIndex as string])">
              {{ replaceEmptyStr(record[column.dataIndex as string]) }}
            </span>
          </template>
        </template>
      </a-table>
    </div>

    <g-pagination
      v-if="!active"
      v-model:offset="pageForm.offset"
      v-model:limit="pageForm.limit"
      :total="pageForm.total"
      @change="getDataList"
    />

    <data-board v-if="active">数据看板</data-board>

    <data-set-form
      ref="dataSetFormRef"
      :title="dataSetFormTitle"
      :ok-button-loading="okButtonLoading"
      :ok-text="dataSetFormOkText"
      @on-ok="handleDataSetSubmit"
    />
    <delete-confirm-dialog
      v-model:show="isDeleteDialogShow"
      msg="此数据集及其包含的所有数据文件将被删除，且不可恢复，请确认操作"
      label="请输入数据集名称"
      :loading="confirmLoading"
      :confirm-name="currentDeleteTaskItem?.taskName"
      @ok="onOkDeleteTask"
    />

    <share-modal
      ref="shareModalRef"
      :submit-api="customerMyDateSetApi.share"
      :remove-user-api="customerMyDateSetApi.removeShareUser"
      :get-list-api="customerMyDateSetApi.getShareList"
    />
  </main-card>
</template>

<script setup lang="ts">
  import { message, TableProps } from 'ant-design-vue'
  import { sizeFilter, storage } from 'g6-fn'
  import { onUnmounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute, useRouter } from 'vue-router'

  import layoutActive from '@/assets/img/customer/layout-active.svg'
  import layoutDefault from '@/assets/img/customer/layout-default.svg'
  import listCheckActive from '@/assets/img/customer/list-check-active.svg'
  import listCheckDefult from '@/assets/img/customer/list-check-default.svg'
  import { DataSetCardData } from '@/components/DataSetCard/indx.vue'
  import { useFileTaskStore } from '@/components/FileTaskCard/upload-store'
  import ShareModal from '@/components/ShareModal/index.vue'
  import useList from '@/hooks/use-list'
  import { customerMyDateSetApi } from '@/services/api'
  import { replaceEmptyStr } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'
  import { checkPermissions } from '@/utils/share'

  import DataSetForm, { DataSetFormState, FormType } from '../../../customer/data-set/components/DataSetForm/index.vue'
  import DataBoard from '../components/DataBoard/index.vue'
  import { headerSearchSelectOptions } from '../options'
  const route = useRoute()
  export interface PageFormType {
    columns?: string
    limit: number
    name?: string
    offset: number
    order?: string
    filter?: string
  }
  export interface MyDataSetCardType {
    createTime: string
    description: string
    fileNum: number
    id: string
    name: string
    size: number
    updateTime: string
  }

  type TaskItem = {
    endTime: null | string
    startTime: null | string
    createTime: string
    id: string
    status: string
    name: string
  }

  type TableDataType = {
    key: string
    name: string
    age: number
    address: string
  }

  const fileTaskStore = useFileTaskStore()
  const router = useRouter()

  const unsubscribe = fileTaskStore.pubSub.subscribe('changeTaskListOptions', (res: any) => {
    console.log(res, 'res')
  })

  const active = ref<boolean>(false)
  const activeSwitch = (): void => {
    active.value = !active.value
    storage.set('DataBoardActive', active.value)
  }
  const activeFlag = (): void => {
    if (route.path === '/my-data-manage/list') {
      const re = storage.get('DataBoardActive') || false
      active.value = re
    }
  }
  activeFlag()
  /*------------------------------------------ table ------------------------------------------*/
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        width: 240
      },
      {
        title: '描述',
        dataIndex: 'description',
        minWidth: 200
      },
      {
        title: '文件大小',
        dataIndex: 'size',
        width: 240
      },
      {
        title: '文件数',
        dataIndex: 'fileNum',
        width: 200
      },
      {
        title: '操作',
        width: 80,
        dataIndex: 'operate'
      }
    ])
  )

  // 表格变化
  const tableChange: TableProps<TableDataType>['onChange'] = (pagination, filters, sorter: any) => {
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    pageForm.value.columns = sorter.field
    if (!sorter.order) {
      pageForm.value.columns = 'createTime'
      pageForm.value.order = 'desc'
    }
    getDataList({ offset: 1 })
  }

  const { pageForm, dataList, loading, getDataList } = useList<PageFormType, TaskItem>(customerMyDateSetApi.list, {
    name: '',
    columns: 'createTime',
    order: 'desc',
    offset: 1,
    limit: 10,
    filter: headerSearchSelectOptions[0].value
  })
  getDataList()

  // 筛选
  const onSelectChange = (value: any) => {
    const columns = value.split('--')[0] || ''
    const order = value.split('--')[1] || ''
    getDataList({ offset: 1, columns, order })
  }

  /*---------------------------------------  数据集新增/编辑 --------------------------------------------*/
  const dataSetFormTitle = ref('创建数据集')
  const dataSetFormOkText = ref('创建')
  const dataSetFormRef = ref<InstanceType<typeof DataSetForm>>()
  const renameId = ref('')
  const handleOpenDataSetForm = (type: 'add' | 'edit', defaultData?: any) => {
    if (type === 'add') {
      dataSetFormTitle.value = '创建数据集'
      dataSetFormOkText.value = '创建'
      dataSetFormRef.value?.open(type, { name: '' })
    } else {
      dataSetFormTitle.value = '编辑数据集'
      dataSetFormOkText.value = '确认'
      renameId.value = defaultData.id
      dataSetFormRef.value?.open(type, { name: defaultData.name, description: defaultData.description })
    }
  }

  // 确认提交
  const okButtonLoading = ref(false)
  const handleDataSetSubmit = async (type: FormType, data: DataSetFormState) => {
    try {
      okButtonLoading.value = true
      type === 'add'
        ? await customerMyDateSetApi.add({ name: data.name, description: data.description }, { isAddUid: true })
        : await customerMyDateSetApi.rename({ id: renameId.value, name: data.name, description: data.description }, { isAddUid: true })

      message.success(type === 'add' ? '新增成功' : '修改成功')
      dataSetFormRef.value?.close()
      getDataList()
    } finally {
      okButtonLoading.value = false
    }
  }

  /*----------------------------------------- 删除 ----------------------------------------*/
  const isDeleteDialogShow = ref(false)
  const currentDeleteTaskItem = ref<any>({
    id: '',
    taskName: ''
  })
  const { loading: confirmLoading, runAsync: runDelCustomerMyDateSet } = useRequest(customerMyDateSetApi.delete)
  const onOkDeleteTask = async () => {
    try {
      await runDelCustomerMyDateSet({ id: currentDeleteTaskItem.value.id }, { isAddUid: true })
      message.success('删除成功')
      isDeleteDialogShow.value = false
      getDataList()
    } catch {
      isDeleteDialogShow.value = false
    }
  }
  const handleDeleteDateSet = (item: MyDataSetCardType | DataSetCardData) => {
    isDeleteDialogShow.value = true
    currentDeleteTaskItem.value.id = item.id
    currentDeleteTaskItem.value.taskName = item.name
  }

  /*----------------------------------------- 分享 --------------------------------*/
  const shareModalRef = ref<InstanceType<typeof ShareModal>>()
  const handleOpenShareModal = (item: MyDataSetCardType | DataSetCardData) => {
    shareModalRef.value?.open({
      id: item.id
    })
  }

  // 概览
  const handleOverview = (item: MyDataSetCardType | DataSetCardData) => {
    router.push({ path: `/my-data-manage/my-data-overview/${item.id}`, query: { name: item.name, id: item.id } })
  }

  /*----------------------------------------- 下载 --------------------------------*/
  const handleDownLoad = async (item: MyDataSetCardType | DataSetCardData) => {
    try {
      await customerMyDateSetApi.download(
        { id: item.id },
        {
          timeout: 300000 //设置超时时长5min
        }
      )
      message.success('成功添加至任务队列')
      fileTaskStore.changeTaskListOptions({
        open: true,
        key: '2',
        showDownFailed: false
      })
    } catch (error) {}
  }

  /*----------------------------------------- 详情 --------------------------------*/
  const handleToDetail = (id: string) => {
    router.push(`/my-data-manage/detail/${id}`)
  }

  onUnmounted(() => {
    unsubscribe()
  })
</script>

<style lang="less" scoped>
  .card-wrap {
    display: grid;
    width: 100%;
    grid-template-columns: repeat(auto-fill, minmax(329px, 1fr));
    grid-gap: 24px 20px;
  }

  .title-wrap {
    display: flex;
    align-items: center;
    height: 38px;
    font-size: 20px;
    color: @text01;
    gap: 0 16px;
    font-style: normal;
    font-weight: 700;
    line-height: 28px;
  }

  .display-btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 12px;
    padding: 3px 2px 3px 3px;
    width: 68px;
    height: 36px;
    background: #fff;
    border: 1px solid rgba(217, 217, 219, 0.5);
    border-radius: 100px;

    /* Shadow/button */
    box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.04);

    .btn {
      display: flex;
      justify-content: center;
      align-items: center;
      padding-right: 8px;
      background: #fff;
      cursor: pointer;
    }

    .active {
      padding-right: 0 !important;
      padding-left: 0 !important;
      width: 30px;
      height: 30px;
      border-radius: 100px;

      /* Shadow/S */
      box-shadow: 0 1px 3px 0 rgba(37, 37, 45, 0.16);
    }
  }
</style>
